<?php

namespace App\Http\Controllers\Backend\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\Users\LoanRequestDetailRequest;
use App\Models\RepaySummary;
use App\Models\UserLoanRequest;
use Illuminate\Http\Request;

class LoanRequestController extends Controller
{
    public function __construct()
    {
//        $this->middleware('auth:backend');
    }

    /**
     * Description:往期成功借款数据列表
     * Author: Sam
     * DateTime: 2019/1/13 22:52
     * @param LoanRequestDetailRequest $request
     * @return mixed
     */
    public function history(LoanRequestDetailRequest $request)
    {
        $user_id = $request->get('user_id');
        $page_size = $request->get('page_size');
        $loan = new UserLoanRequest();
        $loan->setConnection('backend');
        $list = $loan->where('user_id',$user_id)
            ->where('current','<>',1)
            ->whereHas('loanApply',function ($q){
            $q->whereNotNull('loan_time');
        })->with(['loanApply'=>function($q){
            $q->select('id','loan_request_id', 'bank_card_id','loan_time')->with(['bankCard'=>function($q){
                $q->select('id','bank_name_show','card_num');
            }]);
        }])->orderByDesc('created_at')->paginate($page_size);
        $temp = $list->getCollection();
        $temp->map(function($item){
            $item->loan_money = $item->loan_money/100;
            $item->actually_loan_money = $item->actually_loan_money/100;
            $item->count_history = $item->history_count;
            $item->refund = RepaySummary::getRepayAllInfo($item->id);
        });
        $list->setCollection($temp);
        return success($list);
    }

    /**
     * Description:当前期借款情况
     * Author: Sam
     * DateTime: 2019/1/17 11:17
     * @param Request $request
     * @return mixed
     */
    public function current(Request $request){
        $user_id = $request->get('user_id');
        $loan = new UserLoanRequest();
        $loan->setConnection('backend');
        $current = $loan->where('user_id',$user_id)
            ->where('current',1)
            ->with(['loanApply'=>function($q){
                $q->select('id','loan_request_id', 'bank_card_id','loan_time')->with(['bankCard'=>function($q){
                    $q->select('id','bank_name_show','card_num');
                }]);
            }])->first();

        if($current){
            $current->loan_money = $current->loan_money/100;
            $current->actually_loan_money = $current->actually_loan_money/100;
            $current->count_history = $current->history_count;
            $current->refund = RepaySummary::getRepayAllInfo($current->id);
            return success($current);
        }else{
            return failed('');
        }

    }
}
